<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Common;
use App\Http\Controllers\NonPublicVersion\GameConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Payment\Client\Charge;

class Login extends Controller
{
    use Common;

    public function login(Request $request)
    {
        $login_name = $request->input('login_name'); // 手机号或用户名
        $password = $request->input('password');
        $udid = $request->input('udid');
        $sdk_channel_code = $request->input('sdk_channel_code');
        $game_id = $request->input('game_id');

        if ($login_name == '' || $password == ''){
            return $this->json_echo('#false','','缺少参数!');
        }
        if(!$sdk_channel_code)
            return $this->json_echo('#false','','缺少参数!');

        $user = DB::table('user')->where('username', $login_name)->first();
        if (!$user) {
            $user = DB::table('user')->where('phone', $login_name)->first();
        }

        if (!$user) {
            return $this->json_echo('#false','','用户不存在!');
        }
        if ($user->password!= $this->multiMD5($password)){
            json_echo('#false','','密码错误!');
        }

        //$user = D('User')->login($login_name,  $password);
//dd($user);
        if ($user) {
            $user->token = ($udid == $user->udid && $user->token) ? $user->token : $this->multiMD5($login_name.$udid.$password.time());
            $user->udid = $udid;
            // 保存用户到redis
            /*if(Redis::exists('sdk_token_'.$login_name)){
                Redis::rm('sdk_token_'.$login_name);
            }
            Redis::set('sdk_token_'.$login_name, serialize($user));*/

            //$user = service('User')->after_login($user);

            return $this->json_echo('#success', $user, '登陆成功!');
        } else {
            return $this->json_echo('#false', '', '登陆失败!');
        }
        //return [];
    }

    public function register(Request $request)
    {
        $username = $request->input('username');
        $phone = $request->input('phone');
        $password = $request->input('password');
        $captcha = $request->input('captcha');
        $channel_id = $request->input('channel_id'); //渠道id

        #$uid_a = I('post.uid_a');#邀请用户ID
        $sdk_channel_code = $request->input('sdk_channel_code');
        $udid = $request->input('udid');
        $game_id = $request->input('game_id');
        if ((!$username && !$phone) || !$password || ($phone && !$captcha) || (!$channel_id && !$sdk_channel_code)) {
            return $this->json_echo('#false', '', '缺少请求参数!', 0);
        }

        #验证手机
        if ($phone && !preg_match('/^1[0-9]{10}$/', $phone)) {
            return $this->json_echo('#register', '', "请正确输入11位手机号码!");
        }

        //$model = M('user');
        if ($username) {
            $userInfo = DB::table('user')->where('username', $username)->first();//D("User")->get_user_by_username($username);
        }
        if ($phone) {
            $userInfo = DB::table('user')->where('phone', $username)->first();;
        }
        if ($userInfo) {//用户已存在
            return $this->json_echo('#register', '', "该账号已注册过!");
        }

        #验证码验证
        if ($phone) {
            $result = $this->mobile_captch_get($phone, $captcha, 1, 1);
            if ($result['status'] != 1) {
                return $this->json_echo('#register', '', $result['msg']);
            }
        }

        $user_data = array(
            'username' => $username,
            'password' => $this->multiMD5($password),
            'user_type' => 1,
            'udid' => $udid,
            'phone' => $phone,
            'register_ip' => $request->getClientIp(),
            'sdk_channel_code' =>$sdk_channel_code,
            'status' => 0,
            'game_id' => $game_id,
            'create_time' => time(),
            'mac' => $request->input('mac',''),
            'phone_version' => $request->input('phone_version',''),
            'width_pixels' => $request->input('width_pixels',''),
            'height_pixels' => $request->input('height_pixels',''),
            'imei' => $request->input('imei',''),
        );

        $result = DB::table('user')->insertGetId($user_data);
        $new_uid = $result;
        # 初始化昵称
        if ($new_uid) {
            $login_name = $username ? $username : $phone;
            $user = DB::table('user')->where('uid', $new_uid)->first();
            //$user['head'] = $user->head;
            $user->token = $this->multiMD5($login_name.$udid.$password.time());
            $user->udid = $udid;
            // 保存用户到redis
            return $this->json_echo('#success', $user, "您已成功注册!");
        } else {
            return $this->json_echo('#false', '', "注册失败!");
        }

    }

    /**
     * 发送短信验证码接口
     * （0:找回密码 1:注册 2:邀请好友 5:手机验证码快速注册 6：绑定手机验证 7：更换手机验证；   8：手机验证码快速登录）
     */
    public function send_captcha(Request $request) {
        $phone = $request->input('phone');
        $send_type = $request->input('send_type');
        if (!$phone || !isset($send_type)) {
            return $this->json_echo('#false', '', '缺少请求参数', 0);
        }
        $user = DB::table('user')->where('phone', $phone)->first();
        if (($send_type == 1 || $send_type == 5) && $user) {//注册验证
            return $this->json_echo('#false', '', '用户已注册!');
        }
        if ($send_type == 0) {//找回密码
            if (!$user) {
                return $this->json_echo('#false', '', '用户未注册!');
            }
        }
        if ($send_type == 2) { # 邀请好友(分享礼券)
            if ($user) {
                return $this->json_echo('#false', '', '用户已注册!');
            }
        }
        if ($send_type == 6) {//绑定手机验证
            if ($user) {
                return $this->json_echo('#false', '', '您输入的手机号已被绑定！');
            }
        }
        #用户名为手机号码
        if ($phone) {
            $result = $this->mobile_captch_set($request, $send_type);
        }
        if ($result['status']) {
            return $this->json_echo('#success', '', $result['msg']);
        } else {
            return $this->json_echo('#false', '', $result['msg']);
        }
    }

    /**
     * 手机验证码登录
     */
    public function phone_captcha_login (Request $request) {
        $phone = $request->input('phone');
        $captcha = $request->input('captcha');
        $is_public_version = $request->input('is_public_version');
        $channel_id = $request->input('channel_id');
        $sdk_channel_code = $request->input('sdk_channel_code');
        $game_id = $request->input('game_id');
        $udid = $request->input('udid');
        if (!$phone || !$captcha) {
            return $this->json_echo('#false', '', '缺少请求参数!');
        }
        if(!$channel_id && !$sdk_channel_code)
            return $this->json_echo('#false','','缺少参数!');

        #验证手机
        if ($phone && !preg_match('/^1[0-9]{10}$/', $phone)) {
            return $this->json_echo('#false', '', "请正确输入11位手机号码!");
        }

        #验证码验证
        $result = $this->mobile_captch_get($phone, $captcha, 1, 8);
        if ($result['status'] == 0) {
            return $this->json_echo('#false', '', '您输入的验证码不正确!');
        }
        if ($result['status']  == 10) {
            return $this->json_echo('#false', '', '验证码已超时，请重新获取!');
        }
        $user = DB::table('user')->where('phone', $phone)->first();

        if (!$user) {
            $this->phone_captcha_reg($request,'login');
        }

        $user->token = ($udid == $user->udid && $user->token) ? $user->token : multiMD5($phone.$udid.time());
        $user->udid = $udid;
        // 保存用户到redis

        return $this->json_echo('#success', $user, '登陆成功!');
    }

    /**
     * 封装验证码注册方法
     * @param string 登录注册标识
     */
    public function phone_captcha_reg ($request, $flag = 'reg') {

        $flag_msg = $flag == 'reg' ? '您已成功注册!':'登陆成功!';
        $phone = $request->input('phone');
        $is_public_version = $request->input('is_public_version');
        $channel_id = $request->input('channel_id');
        $sdk_channel_code = $request->input('sdk_channel_code');
        $udid = $request->input('udid');
        $game_id = $request->input('game_id');

        $model = M('user');

        $user_data = array(
            'user_type' => 1,
            'udid' => $udid,
            'phone' => $phone,
            'register_ip' => $request->getClientIp(),
            'channel_id' => $channel_id,
            'sdk_channel_code' =>$sdk_channel_code,
            'status' => 0,
            'game_id' => $game_id,
            'create_time' => time(),
            'mac' => $request->input('mac'),
            'phone_version' => $request->input('phone_version'),
            'width_pixels' => $request->input('width_pixels'),
            'height_pixels' => $request->input('height_pixels'),
            'imei' => $request->input('imei'),
        );
        $result = DB::table('user')->insertGetId($user_data);
        $new_uid = $result;
        # 初始化昵称
        //$model->where(array('uid' => $new_uid))->save(array('nickname' => $sys_config['nickname_prefix'] . $new_uid));
        if ($new_uid) {
            $user = D('user')->get_user_by_phone($phone);
            $user['token'] = multiMD5($phone.$udid.time());
            $user['udid'] = $udid;
            // 保存用户到redis
            $redis = myclass('RedisExt', 'Redis');
            $redis->set('access_token_' . $phone,  serialize($user), C('REDIS_TIMEOUT'));//保存用户信息

            if ($is_public_version == 1) {  # 公版
                $user['is_chair'] = $this->sdk_is_chair($user['uid']);
                $this->sdk_get_game_status(I('game_id'), I('sdk_channel_code'));
            }
            service('User')->after_register($user);
            if ($channel_id > 0) {
                // 注册送优惠券信息
                $coupon_user = $this->register_coupon($new_uid);
                if ($coupon_user) {
                    $user['coupon_user'] = $coupon_user;
                }
            }
            $user = service('User')->after_login($user, 1);
            json_echo('#success', $user, $flag_msg);
        } else {
            json_echo('#false', '', "注册失败，请重新注册!");
        }
    }


    /**
     * 手机验证码注册
     */
    public function phone_captcha_register ($request) {
        $phone = $request->input('phone');
        $captcha = $request->input('captcha');

        $channel_id = $request->input('channel_id'); //渠道id
        $sdk_channel_code = $request->input('sdk_channel_code');

        if (!$channel_id && !$sdk_channel_code) {
            json_echo('#false', '', '缺少请求参数!', 0);
        }
        if (!$phone || !$captcha) {
            json_echo('#false', '', '缺少请求参数!', 0);
        }
        #验证手机
        if ($phone && !preg_match('/^1[0-9]{10}$/', $phone)) {
            json_echo('#register', '', "请正确输入11位手机号码!");
        }

        #验证码验证
        if ($phone) {
            $result = $this->mobile_captch_get($phone, $captcha, 1, 5);
            if ($result['status'] == 0) {
                json_echo('#false', '', '您输入的验证码不正确!');
            }
            if ($result['status']  == 10) {
                json_echo('#false', '', '验证码已超时，请重新获取!');
            }
        }
        $this->phone_captcha_reg($request,'reg');

    }

    /**
     * 重置密码
     */
    public function reset_password ($request) {

        $password = $request->input('password');
        $username = $request->input('login_name');

        if (!$username || !$password) {
            json_echo('#false', '', '缺少请求参数!');
        }

        $data = array(
            'update_time' => time(),
            'password' => $this->multiMD5($password)
        );
        $flag = M('user')->where("phone = '{$username}' OR username = '{$username}'")->save($data);

        if ($flag) {
            json_echo('#success', '', '重置成功!');
        } else {
            json_echo('#false', '', '重置失败!');
        }
    }

    /**
     * 找回密码
     */
    public function retrieve_password ($request) {
        $phone = $request->input('phone');
        $captcha = $request->input('captcha');
        $password = $request->input('password');
        $user = D('user')->get_user_by_phone($phone);
        if (!$user) {
            json_echo('#fasle', '', '该账号不存在!');
        }
        $result = $this->mobile_captch_get($phone, $captcha, 1, 0);
        if ($result['status'] != 1) {
            json_echo('#false', '', '输入的验证码不正确!');
        }
        $data = array(
            'update_time' => time(),
            'password' => multiMD5($password)
        );
        $flag = M('user')->where("phone = '{$phone}'")->save($data);

        if ($flag) {
            json_echo('#success', '', '修改成功!');
        } else {
            json_echo('#false', '', '修改失败!');
        }
    }
}